package control;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import model.Color;
import interfaces.IColor;

public class CColor implements IColor {
  private CConnection db;
  
  public CColor(CConnection db) {
	this.db = db;
  }

  @Override
  public boolean create(Color c) throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
	int i = s.executeUpdate("INSERT INTO Color VALUES (" + c.getColorID() + ", '" + c.getDescription() + "')");
	return i > 0;
  }

  @Override
  public boolean update(Color c) throws SQLException, ClassNotFoundException {
	Statement s = db.getStatement();
	int i = s.executeUpdate("UPDATE Color SET Description = '" + c.getDescription() + "' WHERE colorID = " + c.getColorID());
	return i > 0;
  }

  @Override
  public boolean delete(Color c) throws SQLException, ClassNotFoundException {
	Statement s = db.getStatement();
	int i = s.executeUpdate("DELETE FROM Color WHERE colorID = " + c.getColorID());
	return i > 0;
  }

  @Override
  public ArrayList<Color> retrieveByID(int id) throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
    ResultSet res = s.executeQuery("select * from color where colorID = " + id);
    ArrayList<Color> colors = new ArrayList<Color>();
    
    while(res.next()) {
      Color c = new Color();
      c.setColorID(res.getInt("colorID"));
      c.setDescription(res.getString("Description"));
      colors.add(c);
    }
    
    return colors;
  }

  @Override
  public ArrayList<Color> retrieveAll() throws SQLException, ClassNotFoundException {
    Statement s = db.getStatement();
    ResultSet res = s.executeQuery("select * from color");

    ArrayList<Color> colors = new ArrayList<Color>();
	    
    while(res.next()) {
      Color c = new Color();
      c.setColorID(res.getInt("colorID"));
      c.setDescription(res.getString("Description"));
      colors.add(c);
    }

    return colors;
  }
}
